import Vue from "vue";
import Router from "vue-router";
import Layout from "../layouts/default.vue";
// import Layout from "../layout/index.vue";

let routers = [
  {
    path: "/",
    name: "index",
    component: Layout,
    children: [
      {
        path: "/",
        name: "home",
        component: resolve => require(["@/pages/index.vue"], resolve)
      },
      {
        path: "/user",
        component: resolve => require(["@/pages/user/index.vue"], resolve)
      }
    ]
  },
  {
    path: "/login",
    name: "login",
    component: () =>
      import(/* webpackChunkName: "login" */ "@/pages/login/index.vue")
    // 也可以使用这一种写法， 路由分割模式
    //  component: r => require.ensure([], () => r(require('@/page/index')), 'index')
  },
  {
    path: "/404",
    name: "404",
    component: () => import(/* webpackChunkName: "404" */ "@/pages/404.vue")
    // 也可以使用这一种写法， 路由分割模式
    //  component: r => require.ensure([], () => r(require('@/page/index')), 'index')
  }
];

Vue.use(Router);

let R = new Router({
  routes: routers,
  mode: "history",
  scrollBehavior(to, from, savedPosition) {
    console.log(to, from, savedPosition);
    return { x: 0, y: 0 };
  }
});
import store from "../store";
R.beforeEach(async (to, from, next) => {
  console.log("store", store, to, from);
  if (to.path.indexOf("login") !== -1) {
    next();
    return
  }
  if (to.path.indexOf("login") === -1 && !store.state.user.token) {
    store.dispatch("user/FedLogOut", false);
    return next("/login");
  } else {
    Promise.all([
      store.dispatch("user/getUserInfo"),
      store.dispatch("permissList")
    ]).then(() => {
      next();
    });
  }
});
export default R;
